﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Magic.Redis;

public static class RedisServiceCollectionExtensions
{
    public static IServiceCollection AddRedis(this IServiceCollection services)
    {
        // 配置验证
        ConfigureRedisOptions(services);

        var options = services.BuildServiceProvider().GetService<IOptions<RedisOptions>>().Value;
        var connStr = options.ConnectionString;
        services.AddSingleton<IRedisClient, CsRedisCoreClient>(sp =>
        {
            var rds = new CsRedisCoreClient(sp.GetRequiredService<ILoggerFactory>());
            rds.Initialization(connStr);
            return rds;
        });
        return services;
    }

    private static void ConfigureRedisOptions(IServiceCollection services)
    {
        // 配置验证
        services.AddOptions<RedisOptions>()
                .BindConfiguration("Redis")
                .ValidateDataAnnotations();
    }
}
